package com.boarsoft.boar.sys.action;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.LogonI;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.auth.TokenAuth;
import com.boarsoft.boar.auth.TxtPwdAuth;
import com.boarsoft.boar.common.Constants;
import com.boarsoft.boar.common.Logon;
import com.boarsoft.boar.sys.SysUserBiz;
import com.boarsoft.boar.sys.entity.SysUser;
import com.boarsoft.common.Authorized;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.common.util.JsonUtil;
import com.boarsoft.web.login.Logined;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@RestController
@RequestMapping("/sys/user")
public class SysUserAction {
	@Autowired
	private SysUserBiz sysUserBiz;
	@Autowired
	private TokenAuth tokenAuth;
	@Autowired
	private TxtPwdAuth txtPwdAuth;

	/**
	 * 删除用户已停用的用户
	 * 
	 * @return
	 */
	@RequestMapping("/delete.do")
	@Authorized(code = "sys.user.delete")
	public ReplyInfo<Object> delete(String id) {
		SysUser o = sysUserBiz.get(id);
		if (o != null && o.getStatus() == SysUser.STATUS_NOUSE) {
			sysUserBiz.delete(o.getId());
			return ReplyInfo.SUCCESS;
		}
		return Constants.REPLY_WARN_INVALID;
	}

	/**
	 * 查询用户列表
	 * 
	 * @return
	 */
	@JsonIgnoreProperties(value = { "roles", "password" })
	@RequestMapping("/list.do")
	@Authorized(code = "sys.user.list")
	public ReplyInfo<Object> list(@Logined LogonI<String> logon, String corpId, String deptId, String key, int pageNo, int pageSize,
			String orderBy) {
		PagedResult<SysUser> pr = sysUserBiz.list(corpId, deptId, key, pageNo, pageSize, orderBy);
		return new ReplyInfo<Object>(true, pr);
	}

	@RequestMapping("/save.do")
	@Authorized(code = "sys.user.save")
	public ReplyInfo<Object> save(SysUser o) {
		if (Util.strIsEmpty(o.getId())) {
			return this.add(o);
		}
		return this.modify(o);
	}

	/**
	 * 管理员添加系统用户
	 * 
	 * @return
	 */
	@RequestMapping("/add.do")
	@Authorized(code = "sys.user.add")
	public ReplyInfo<Object> add(SysUser o) {
		// 除了超级管理员，其它用户的corpId均不允许为空
		if (Util.strIsEmpty(o.getCorpId())) {
			// return Constants.REPLY_WARN_INVALID;
		}
		// 集团内，员工编号（code）是唯一的
		if (sysUserBiz.add(o)) {
			return ReplyInfo.SUCCESS;
		}
		return Constants.REPLY_INFO_DUPLICATED;
	}

	/**
	 * 管理员修改员工信息
	 * 
	 * @param a
	 * @return
	 */
	@RequestMapping("/modify.do")
	@Authorized(code = "sys.user.modify")
	public ReplyInfo<Object> modify(SysUser a) {
		SysUser o = sysUserBiz.get(a.getId());
		o.setName(a.getName());
		o.setPosition(a.getPosition());
		o.setEmail(a.getEmail());
		o.setPhone(a.getPhone());
		o.setCorpId(a.getCorpId());
		o.setDeptId(a.getDeptId());
		o.setStatus(a.getStatus());
		sysUserBiz.update(o);
		return ReplyInfo.SUCCESS;
	}

	/**
	 * 员工自己修改自己的信息
	 * 
	 * @param a
	 * @return
	 */
	@RequestMapping("/update.do")
	@Authorized(code = "sys.user.update")
	public ReplyInfo<Object> update(@Logined LogonI<String> logon, SysUser a) {
		SysUser o = sysUserBiz.get(logon.getId());
		o.setName(a.getName());
		o.setPosition(a.getPosition());
		o.setEmail(a.getEmail());
		o.setPhone(a.getPhone());
		sysUserBiz.update(o);
		return ReplyInfo.SUCCESS;
	}
	
	@RequestMapping("/status.do")
	@Authorized(code = "sys.user.status")
	public ReplyInfo<Object> status(String id, short status) {
		SysUser o = sysUserBiz.get(id);
		o.setStatus(status);
		sysUserBiz.update(o);
		return ReplyInfo.SUCCESS;
	}

	/**
	 * 登录 用户登录无需检查权限
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/login.do")
	// @DaoSharding(policy = "default", key = "auth")
	public ReplyInfo<Object> login(HttpSession session, HttpServletResponse res, String verifyCode, String code,
			String password) throws Exception {
		Integer fc = (Integer) session.getAttribute("fc");
		if (fc == null) {
			fc = 0;
		} else if (fc >= 3) {
			String vc = String.valueOf(session.getAttribute("vc"));
			if (Util.strIsEmpty(verifyCode) || !verifyCode.equals(vc)) {
				return new ReplyInfo<Object>(Constants.INFO_LOGIN_FAILED, String.valueOf(fc));
			}
		}
		// txtPwdAuth 会在cache中缓存此用户的信息
		ReplyInfo<Object> ri = txtPwdAuth.authorize(code, password);
		if (ri.isSuccess()) {
			Logon lg = (Logon) ri.getData();
			String token = lg.getToken();
			session.setAttribute("fc", 0);
			// 在客户端保存一个cookie
			Cookie tc = new Cookie("token", token);
			tc.setMaxAge(60 * 60 * 24 * 7);// 保留七天
			tc.setPath("/");
			res.addCookie(tc);
			//
			return new ReplyInfo<Object>(true, lg);
		}
		session.setAttribute("fc", fc + 1);
		return new ReplyInfo<Object>(Constants.INFO_LOGIN_FAILED);
	}

	/**
	 * 注销，@Authorized(code = "")表示要注入logon但不需要权限
	 * 
	 * @return
	 */
	@RequestMapping("/logout.do")
	@Authorized(code = "")
	public ReplyInfo<Object> logout(@Logined LogonI<String> logon, HttpServletResponse response, String token) {
		Cookie tc = new Cookie("token", "");
		tc.setMaxAge(1);// 立即失效
		tc.setPath("/");
		response.addCookie(tc);
		//
		if (logon != null) {
			tokenAuth.logout(logon.getId(), token);
		}
		return ReplyInfo.SUCCESS;
	}

	/**
	 * 用户详细信息
	 * 
	 * @return
	 */
	@RequestMapping("/get.do")
	@Authorized(code = "sys.user.get")
	public ReplyInfo<String> info(@Logined LogonI<String> logon) {
		SysUser o = sysUserBiz.get(logon.getId());
		return new ReplyInfo<String>(true, JsonUtil.from(o, "roles,password"));
	}
}